# 财务明细数据服务类  flydragon
class Finances::IndexService
  delegate :params, :session, :raw, :link_to, :number_to_currency, to: :@view
  include HeiPisService

  #view 视图上下文
  #company 公司
  def initialize(view,company)
    @view = view
    @company = company
  end

  #执行方法 返回值
  def call

    page = params[:page].to_i
    pagesize = params[:pagesize].to_i
    studio_id = params[:studio_id]
    finance_type = params[:finance_type]
    finance_category = params[:finance_category]
    setdate = params[:setdate]
    
    filter_sql = "company_id = :company_id"
    filter_params = {company_id: @company.id}

    if studio_id.present?
      filter_sql += " and studio_id = :studio_id"
      filter_params[:studio_id] = studio_id
    end

    if finance_type.present?
      filter_sql += " and finance_type = :finance_type"
      filter_params[:finance_type] = finance_type
    end

    if finance_category.present?
      filter_sql += " and finance_category = :finance_category"
      filter_params[:finance_category] = finance_category
    end

    if setdate.present?
      filter_sql += " and date_format(setdate,'%Y-%m') = :setdate"
      filter_params[:setdate] = setdate
    end


    searchRecord = Finance.includes(:studio).where(filter_sql,filter_params)
    
    count = searchRecord.count
    datas = searchRecord.offset((page-1)*pagesize).limit(pagesize).order("created_at desc").map do |record|  
       
      data = {}
      data[:setdate] = record.setdate
      data[:finance_type] = record.finance_type
      data[:finance_category] = record.finance_category
      data[:amount] = record.amount
      data[:studio_name] = record.get_studio_name
      if !record.is_system
        data[:op] =  %Q{
          <span>[</span>#{link_to "编辑", @view.edit_admin_finance_path(record), remote: true}<span>]</span>
          <div class="remarks-de">
            <em>备注</em>
            <div>
              <i></i>
              <b>备注:</b>
              <p>#{record.remark.html_safe}</p>
            </div>
          </div>
          }
      else
        data[:op] =  %Q{
          <div class="remarks-de">
            <em>备注</em>
            <div>
              <i></i>
              <b>备注:</b>
              <p>#{record.remark.html_safe}</p>
            </div>
          </div>
          }
      end

      

      data
    end

    DataTableResult.new(searchRecord.count,datas)
  end


end
